package com.qm.xml;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.Iterator;

/**
 * @Author: wb
 * @CreateTime: 2022-11-18  08:42
 * @Description: java 操作xml
 */
public class MyDom {
    public static void main(String[] args) throws DocumentException {
        SAXReader reader = new SAXReader();
        //读入文档流
        Document document = reader.read(new File("mydom.xml"));
        //获取根节点
        Element root = document.getRootElement();
        //拿到attribute属性的值
        System.out.println("指定的属性---" + root.attributeValue("city"));
        // 获取所有属性
        for (Attribute attribute : root.attributes()) {
            System.out.println("所有的属性-->"+ attribute.getName()+"===" + attribute.getValue());
        }
        // 获取所有的子节点
        Iterator<Element> iterator1 = root.elementIterator();
        while (iterator1.hasNext()) {
            Element element = iterator1.next();
            System.out.println("所有的子元素-->" + element.getName());
        }
        //解析指定student节点
        for (Iterator<Element> iterator = root.elementIterator("student"); iterator.hasNext(); ) {
            Element eStudent = iterator.next();
            System.out.println("指定的student元素-->" + eStudent.getName());
            System.out.println("指定的属性---" + eStudent.attributeValue("name"));
        }
    }

}

